import React, { useState, useEffect } from "react";
import { useSelector } from 'react-redux';
import { CRow, CFormInput, CFormSelect, CButton, CCol, CFormLabel } from '@coreui/react';

const AddEmployee = () => {
    const [roles, setRoles] = useState([]);
    const [idRole, setIDRole] = useState(0);
    const [message, setMessage] = useState('');
    const token = useSelector((state) => state.token);
    const [username, setUsername] = useState('');
    const [login, setLogin] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');

    useEffect(() => {
        fetchRoles();
    }, []);

    const fetchRoles = async () => {
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/roles/`,
                {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                }
            );
            const data = await response.json();
            setRoles(data);
            setIDRole(data[0].id);
        } catch (error) {
            console.error("Failed to fetch roles:", error);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (password!== confirmPassword) {
            setMessage('Пароли не совпадают');
            return;
        }
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    username,
                    login,
                    password,
                    role_id: idRole
                }),
            });
    
            if (!response.ok) {
                const jsonResponse = await response.json(); // Преобразуем ответ в объект JSON
                throw new Error(jsonResponse.detail); // Бросаем исключение с деталями ошибки
            }
    
            setMessage('Пользователь успешно добавлен');
        } catch (error) {
            setMessage(`Ошибка при добавлении пользователя: ${error.message}`);
        }
    };
    
    return (
        <div>
            <h1>Добавить сотрудника</h1>
            <br></br>
            <form onSubmit={handleSubmit}>
                <CRow>
                    <CCol xs={6}>
                        <CFormInput
                            type="text"
                            placeholder="Фамилия Имя Отчество"
                            aria-label="Username"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                    </CCol>
                </CRow>
                <br></br>
                <CRow>
                    <CCol xs={6}>
                        <CFormInput
                            type="text"
                            placeholder="Логин"
                            aria-label="Login"
                            value={login}
                            onChange={(e) => setLogin(e.target.value)}
                        />
                    </CCol>
                </CRow>
                <br></br>
                <CRow>
                    <CCol xs={6}>
                        <CFormInput
                            type="password"
                            placeholder="Пароль"
                            aria-label="Password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                        />
                    </CCol>
                </CRow>
                <br></br>
                <CRow>
                    <CCol xs={6}>
                        <CFormInput
                            type="password"
                            placeholder="Повторите пароль"
                            aria-label="Password"
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                        />
                    </CCol>
                </CRow>
                <br></br>
                <CRow>
                    <CCol xs={6}>
                        <CFormSelect
                            aria-label="Assign role to employee"
                            value={idRole}
                            onChange={(e) => setIDRole(e.target.value)}
                        >
                            {roles.map((role) => (
                                <option key={role.id} value={role.id}>{role.fullname}</option>
                            ))}
                        </CFormSelect>
                    </CCol>
                </CRow>
                <br></br>
                <CRow>
                    <CCol xs={6}>
                        <CButton color="light" variant="outline" type="submit">Добавить</CButton>
                    </CCol>
                </CRow>
            </form>
            <CRow>
                <CFormLabel htmlFor="staticEmail" className="col-sm-12 col-form-label">{message}</CFormLabel>
            </CRow>
        </div>
    );
};

export default AddEmployee;
